
//
// 20120825 - AH - Created.
// 20120906 - AH - Missing java doc.
//

package org.japril.jhut.swing;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.CharArrayWriter;
import java.io.PrintWriter;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.japril.jhut.framework.JhutTest;

/**
 * <p>
 *   Dialog to show info about a test.
 * </p>
 * @author Arne Halvorsen (AH)
 */
@SuppressWarnings("serial")
public final class TestInfoDialog extends JDialog 
{
  private final JTextField m_name=new JTextField(30);
  
  private final JTextArea m_trace=new JTextArea();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public TestInfoDialog(){ buildGui(); }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param p Dialog's parent.
   */
  public TestInfoDialog(Frame p){ super(p); buildGui(); }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param p Dialog's parent.
   */
  public TestInfoDialog(Dialog p){ super(p); buildGui(); }
  
  private void buildGui()
  {
    setTitle("Test Info");
    
    Container c=getContentPane();
    c.setLayout(new BorderLayout());
    
    c.add(m_name, BorderLayout.NORTH);
    c.add(new JScrollPane(m_trace), BorderLayout.CENTER);
    
    JPanel buttons=new JPanel(new FlowLayout(FlowLayout.CENTER));
    buttons.add
    (
      new JButton
      (
        new AbstractAction("Close")
        {
          public void actionPerformed(ActionEvent e){ dispose(); }
        }
      )
    );
    
    c.add(buttons, BorderLayout.SOUTH);
    
    pack();
    setSize(500, 500);
  }
  
  /**
   * <p>
   *   Shows dialog for given test.
   * </p>
   * @param test Test, if {@code null} shows dialog with no content.
   */
  public void show(JhutTest test)
  {
    m_name.setText("");
    m_trace.setText("");
    
    if (test!=null)
    {
      m_name.setText(test.getName());
      
      String ttext="";
      if (!test.performed())
      {
        ttext="Not performed";
      }
      else if (test.ok())
      {
        ttext="Ok";
      }
      else
      {
        Throwable err=test.getError();
        ttext=getStackTrace(err);
      }
      m_trace.setText(ttext);
    }
    
    setVisible(true);
  }
  
  private static String getStackTrace(Throwable t)
  {
    CharArrayWriter caw=new CharArrayWriter();
    PrintWriter pw=new PrintWriter(caw);
    t.printStackTrace(pw);
    pw.flush();
    return caw.toString();
  }
  
}
